import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path_provider/path_provider.dart';
import 'package:untitled/utils/SnackBarHepler.dart';

import '../utils/DioUtil.dart';

class TestNetPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _TestNetPageState();
  }
}

class _TestNetPageState extends State<TestNetPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('网络请求')),
      body: SizedBox.expand(
        child: Column(
          children: [
            OutlinedButton(
              onPressed: () {
                testGet1();
              },
              child: Text('list 数据请求'),
            ),
            OutlinedButton(
              onPressed: () {
                testGet3();
              },
              child: Text('工具类 数据请求'),
            ),
            OutlinedButton(
              onPressed: () {
                testGet2();
              },
              child: Text('单 数据请求'),
            ),
            OutlinedButton(
              onPressed: () {
                testPost1();
              },
              child: Text('post 请求'),
            ),
            OutlinedButton(
              onPressed: () {
                testPostUpload();
              },
              child: Text('上传文件 '),
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                OutlinedButton(
                  onPressed: () {
                    testDown();
                  },
                  child: Text('下载文件 '),
                ),
                OutlinedButton(
                  onPressed: () {
                    if (downCancelToken != null) {
                      downCancelToken!.cancel();
                    }
                  },
                  child: Text('取消下载  '),
                ),
              ],
            ),
            SizedBox(
              width: 40,
              height: 40,
              child: Stack(
                alignment: Alignment(0, 0),
                children: [
                  CircularProgressIndicator(value: uploadProgress),
                  Text(
                    "${(uploadProgress * 100).toStringAsFixed(0)}%",
                    style: TextStyle(fontSize: 12),
                  ),
                ],
              ),
            ),
            SizedBox(
              width: 40,
              height: 40,
              child: Stack(
                alignment: Alignment(0, 0),
                children: [
                  CircularProgressIndicator(
                    value: downProgress,
                    color: Colors.grey,
                    valueColor: AlwaysStoppedAnimation(Colors.red),
                  ),
                  Text(
                    "${(downProgress * 100).toStringAsFixed(0)}%",
                    style: TextStyle(fontSize: 12),
                  ),
                ],
              ),
            ),
            _userInfo == null
                ? SizedBox()
                : Card(
                    child: Container(
                      alignment: Alignment.center,
                      width: double.infinity,
                      height: 44,
                      child: Text(
                        '用户：${_userInfo?.name}  age:${_userInfo?.age}  userId is ${_userInfo?.userId}',
                      ),
                    ),
                  ),
            _userInfo2 == null
                ? SizedBox()
                : Card(
                    child: Container(
                      color: Colors.blue[100],
                      alignment: Alignment.center,
                      width: double.infinity,
                      height: 44,
                      child: Text(
                        '注册用户成功：${_userInfo2?.name}  age:${_userInfo2?.age}  userId is ${_userInfo2?.userId}',
                      ),
                    ),
                  ),
            Expanded(
              child: ListView.builder(
                itemCount: _userInfoList.length,
                itemBuilder: (BuildContext context, int index) {
                  UserInfo info = _userInfoList[index];

                  String name = info.name;
                  int age = info.age;
                  return ListTile(
                    title: Text(name),
                    subtitle: Text('年龄是 $age'),
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  UserInfo? _userInfo2;
  Future<void> testPost1() async {
    String url = 'http://192.168.3.16:8081/football-api/api/test/regist';

    BaseOptions options = BaseOptions(
      connectTimeout: Duration(seconds: 5),
      receiveTimeout: Duration(seconds: 3),
      headers: {
        'token': '9985847584385394656455',
        'Content-Type': 'application/json',
      },
    );

    Dio dio = Dio(options);
    Response response = await dio.post(
      url,
      data: {'userId': 7777, 'name': '李四', 'age': 24},
    );

    int statusCode = response.statusCode ?? 400;
    String message = response.statusMessage ?? '';
    dynamic data = response.data;
    if (statusCode == 200) {
      if (data != null) {
        num code = data['code'] ?? -1;
        String msg = data['msg'] ?? '';
        dynamic itemData = data['data'];
        if (code == 0) {
          if (itemData != null) {
            UserInfo userInfo = UserInfo.fromMap(itemData);
            _userInfo2 = userInfo;
            setState(() {});
          } else {
            SnackBarHelper.showSuccess(context, '加载完成');
          }
        } else {
          SnackBarHelper.showError(context, msg);
        }
      } else {
        SnackBarHelper.showError(context, '网络请求异常');
      }
    } else {
      SnackBarHelper.showError(context, message);
    }
  }

  UserInfo? _userInfo;
  Future<void> testGet2() async {
    String url = 'http://192.168.3.16:8081/football-api/api/test/info';
    Dio dio = Dio();
    Response response = await dio.get(url, queryParameters: {'userId': 7777});

    int statusCode = response.statusCode ?? 400;
    String message = response.statusMessage ?? '';
    dynamic data = response.data;
    if (statusCode == 200) {
      if (data != null) {
        num code = data['code'] ?? -1;
        String msg = data['msg'] ?? '';
        dynamic itemData = data['data'];
        if (code == 0) {
          if (itemData != null) {
            UserInfo userInfo = UserInfo.fromMap(itemData);
            _userInfo = userInfo;
            setState(() {});
          } else {
            SnackBarHelper.showSuccess(context, '加载完成');
          }
        } else {
          SnackBarHelper.showError(context, msg);
        }
      } else {
        SnackBarHelper.showError(context, '网络请求异常');
      }
    } else {
      SnackBarHelper.showError(context, message);
    }

    return;
  }

  List<UserInfo> _userInfoList = [];
  Future<void> testGet1() async {
    Dio dio = Dio();
    Response response = await dio.get(
      'http://192.168.3.16:8081/football-api/api/test/list',
    );
    print(response.toString());

    int statusCode = response.statusCode ?? 400;
    String message = response.statusMessage ?? '';
    dynamic data = response.data;
    if (statusCode == 200) {
      if (data != null) {
        num code = data['code'] ?? -1;
        String msg = data['msg'] ?? '';
        dynamic itemData = data['data'];

        if (itemData != null && itemData is List) {
          List list = itemData;
          List<UserInfo> userInfoList = [];
          for (int i = 0; i < list.length; i++) {
            dynamic obj = list[i];
            //解析
            UserInfo info = UserInfo.fromMap(obj);
            //添加到列表中
            userInfoList.add(info);
          }
          print('解析完成');
          _userInfoList = userInfoList;
          setState(() {});
        }
      }
    }
  }

  double uploadProgress = 0.0;
  void testPostUpload() async {
    //相册选择
    ImagePicker imagePicker = ImagePicker();
    //选择图片
    XFile? file = await imagePicker.pickImage(source: ImageSource.gallery);
    if (file == null) {
      return;
    }

    //获取路径
    String filePath = file.path;
    print('filePath $filePath');

    String url = 'http://192.168.3.16:8081/football-api/api/test/upload';
    Dio dio = Dio();

    //构建请求体
    FormData formData = FormData.fromMap({
      'filename': '代码测试',
      'description': '这里是描述 ',
      'file': await MultipartFile.fromFile(filePath),
    });

    //发送请求
    Response response = await dio.post(
      url,
      //数据
      data: formData,
      //上传进度
      onSendProgress: (int count, int total) {
        print('上传进度 $count  $total');
        uploadProgress = count * 1.0 / total;
        setState(() {});
      },
      onReceiveProgress: (int count, int total) {
        print('下载进度 $count  $total');
      },
    );

    print(response.toString());

    int statusCode = response.statusCode ?? 400;
    String message = response.statusMessage ?? '';
    dynamic data = response.data;
    if (statusCode == 200) {
      print('上传成功 $data');
    } else {
      print('上传失败 $message');
    }
  }

  CancelToken? downCancelToken;
  double downProgress = 0;
  Future<void> testDown() async {
    String urlPath = 'http://www.zqycscc.cn/test.apk';

    final Directory tempDir = await getTemporaryDirectory();

    downCancelToken = CancelToken();
    //保存路径
    String savePath = '${tempDir.path}/local.apk';
    print('保存路径  $savePath');

    Dio dio = Dio();
    try {
      Response response = await dio.download(
        urlPath,
        savePath,
        cancelToken: downCancelToken,
        onReceiveProgress: (int count, int total) {
          //计算下载 进度
          downProgress = count * 1.0 / total;
          setState(() {});
        },
      );

      print(response.toString());

      int statusCode = response.statusCode ?? 400;
      String message = response.statusMessage ?? '';
      dynamic data = response.data;
      if (statusCode == 200) {
        print('下载成功 $data');
      } else {
        print('下载失败 $message');
      }
    } on DioException catch (e) {
      print(e);
    }
  }

  DioUtil _dioUtil = DioUtil();
  //调用工具类
  Future<void> testGet3() async {
    try {
      String url = 'http://192.168.3.16:8081/football-api/api/test/list';
      Response response = await _dioUtil.get(url);
      int statusCode = response.statusCode ?? 400;

      if (statusCode == 200) {
        if (response.data != null) {
          if (response.data['data'] != null) {
            List list = response.data['data'];
            _userInfoList = list.map((e) => UserInfo.fromMap(e)).toList();
            setState(() {});
            SnackBarHelper.showSuccess(context, '请求成功');
          } else {
            SnackBarHelper.showSuccess(context, '请求完成');
          }
        } else {
          SnackBarHelper.showSuccess(context, '请求完成');
        }
      } else {
        SnackBarHelper.showError(context, '请求错误');
      }
    } catch (e) {
      SnackBarHelper.showError(context, '请求错误');
    }

    return;
  }
}

class UserInfo {
  String name = '';
  int age = 0;
  var userId;
  UserInfo.fromMap(dynamic map) {
    name = map['name'] ?? '';
    age = map['age'] ?? 0;
    userId = map['userId'];
  }
}
